package com.cn.springcloudwechat.common.utils.weixin.core;

import com.cn.springcloudwechat.common.utils.SpringWebContextUtil;
import com.cn.springcloudwechat.common.utils.weixin.vo.event.*;
import com.cn.springcloudwechat.common.utils.weixin.vo.message.*;
import com.cn.springcloudwechat.common.utils.weixin.vo.push.SentAllJobEvent;
import com.cn.springcloudwechat.common.utils.weixin.vo.push.SentTmlJobEvent;
import com.cn.springcloudwechat.model.YmUser;
import com.cn.springcloudwechat.model.proxy.YmProxyStation;
import com.cn.springcloudwechat.model.proxy.YmProxyUser;
import com.cn.springcloudwechat.model.vaccinestion.YmVStation;
import com.cn.springcloudwechat.model.weixin.event.WxEventClick;
import com.cn.springcloudwechat.model.weixin.menu.WxMenu;
import com.cn.springcloudwechat.service.personalcenter.service.YmUserService;
import com.cn.springcloudwechat.service.proxy.ProxyStationService;
import com.cn.springcloudwechat.service.proxy.ProxyUserService;
import com.cn.springcloudwechat.service.vaccinstation.VaccineStationService;
import com.cn.springcloudwechat.service.weixin.menu.WxMenuService;
import com.cn.springcloudwechat.springUtil.SpringUtil;
import org.apache.commons.lang3.StringUtils;
import org.nutz.lang.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


/**
 * 微信消息,事件处理器(实际生产中需要重写)
 * 
 * @author 
 * @since 2.0
 */
@Service("WechatHandler")
public class WechatDefHandler implements WechatHandler {

    @Override
    public BasicMsg defMsg(BasicMsg bm) {
        System.out.println("新消息类型");
        TextMsg tm = new TextMsg(bm);
        tm.setContent(bm.getMsgType());
        return tm;
    }

    @Override
    public BasicMsg defEvent(BasicEvent be) {
        System.out.println("新事件类型");
        TextMsg tm = new TextMsg(be);
        tm.setContent(Strings.join("\n", be.getEvent(), be.getEventKey()));
        return tm;
    }

    @Override
    public BasicMsg text(TextMsg tm) {
        System.out.println("处理文本消息");
        return tm;
    }

    @Override
    public BasicMsg image(ImageMsg im) {
        System.out.println("处理图像消息");
        return im;
    }

    @Override
    public BasicMsg voice(VoiceMsg vm) {
        System.out.println("处理音频消息");
        TextMsg tm = new TextMsg(vm);
        tm.setContent(Strings.join("\n", vm.getMediaId(), vm.getFormat(), vm.getRecognition()));
        return tm;
    }

    @Override
    public BasicMsg video(VideoMsg vim) {
        System.out.println("处理视频消息");
        TextMsg tm = new TextMsg(vim);
        tm.setContent(Strings.join("\n", vim.getMsgType(), vim.getMediaId(), vim.getThumbMediaId()));
        return tm;
    }

    @Override
    public BasicMsg shortVideo(VideoMsg vim) {
        System.out.println("处理短视频消息");
        TextMsg tm = new TextMsg(vim);
        tm.setContent(Strings.join("\n", vim.getMsgType(), vim.getMediaId(), vim.getThumbMediaId()));
        return tm;
    }

    @Override
    public BasicMsg location(LocationMsg lm) {
        System.out.println("处理地理位置消息");
        TextMsg tm = new TextMsg(lm);
        tm.setContent(Strings.join("\n",
                                   lm.getX(),
                                   lm.getY(),
                                   String.valueOf(lm.getScale()),
                                   lm.getLabel()));
        return tm;
    }

    @Override
    public BasicMsg link(LinkMsg lm) {
        System.out.println("处理链接消息");
        NewsMsg news = new NewsMsg(lm);
        Article art = new Article();
        art.setTitle(lm.getTitle());
        art.setDescription(lm.getDescription());
        //art.setPicUrl("http://j2ee.u.qiniudn.com/mpsdk4j-logo.png-aliassmall");
        art.setUrl(lm.getUrl());
        news.setArticles(Arrays.asList(art));
        return news;
    }

    @Override
    public BasicMsg eClick(MenuEvent me) {
        ApplicationContext ac = SpringUtil.getApplicationContext();
        WxMenuService wms = (WxMenuService) ac.getBean("WxMenuService");
        WxMenu wxMenu=wms.getWxMenuByKeyId(me.getEventKey());
        if(wxMenu!=null){
        	String selectType=wxMenu.getSelectType();
            List<WxEventClick> wxecs= wxMenu.getItems();
            if(wxecs!=null &&wxecs.size()>0){
            	if("text".equals(selectType)){
                	TextMsg tm = new TextMsg(me);
                    tm.setContent(wxecs.get(0).getContent());
                    return tm;
                }else if("imageText".equals(selectType)){
                	NewsMsg news = new NewsMsg(me);
                	List<Article> articles =new ArrayList<Article>();
                	for(WxEventClick wxec:wxecs){
                		Article art = new Article(wxec.getTitle(),wxec.getContent(),wxec.getPicUrl(),wxec.getUrl());
                        articles.add(art);
                	}
                    news.setArticles(articles);
                    return news;
                }else if("image".equals(selectType)){
                	NewsMsg news = new NewsMsg(me);
                    Article art = new Article();
                    art.setTitle("");
                    art.setDescription("");
                    art.setPicUrl(wxecs.get(0).getPicUrl());
                    news.setArticles(Arrays.asList(art));
                	return news;
                }
            }
        }     
        TextMsg tm = new TextMsg(me);
    	tm.setContent("对不起,暂时不能提供服务");
    	return tm;
    }

    @Override
    public void eView(MenuEvent me) {
        System.out.println("处理菜单视图事件消息");
    }

    @Override
    public BasicMsg eSub(BasicEvent be) {
        TextMsg tm = new TextMsg(be);
        System.out.println("未关注点击关注推送事件");
        System.out.println(be.toString());
        if(StringUtils.isNotBlank(be.getEventKey())&&be.getEventKey()!=""){
            //扫码未关注事件
            String param = be.getEventKey().substring(be.getEventKey().indexOf("_")+1);
        }else{
            tm.setContent(
                    "欢迎关注“疫苗接种”平台\n\n"
            );
        }

        return tm;
    }



    @Override
    public void eUnSub(BasicEvent be) {
        System.out.println("取消关注事件");
    }

    @Override
    public BasicMsg eScan(ScanEvent se) {
        //扫码关注事件
        System.out.println("扫码关注推送事件");
        System.out.println(se.toString());
        TextMsg tm = new TextMsg(se);
        String param=se.getEventKey();
        if(StringUtils.isNotBlank(param)&&param!=""){
            String[] split = param.split("&");
            //类型
            String type=split[0].substring(split[0].indexOf("=")+1);

            //代理id
            String pm1=split[1];
            //用户openid
            String openid=se.getFromUserName();
            //查询用户
            YmUserService ymUserService=(YmUserService) SpringUtil.getBean("YmUserService");
            YmUser user = ymUserService.getUserByOpenId(openid);
            //用户id
            Long userId=user.getUserId();
            if(type.equals("0")){
                System.out.println("用户代理");
                //用户代理
                ProxyUserService proxyUserService = ((ProxyUserService) SpringUtil.getBean("ProxyUserService"));
                YmProxyUser ymProxyUser=new YmProxyUser();
                ymProxyUser.setUserId(userId);
                ymProxyUser.setParentId(Long.parseLong(pm1));
                Integer check = proxyUserService.selectCheckProxyUser(ymProxyUser);
                if(check==0){
                    Integer result = proxyUserService.insertProxyUser(ymProxyUser);
                    if(result>0){
                        YmUser userProxy = ymUserService.selectByPrimaryKey(Long.parseLong(pm1));
                        tm.setContent("你的代理人:"+userProxy.getNickname());
                    }else{
                        System.out.println("新增代理失败");
                    }
                }else{
                    tm.setContent("亲爱的用户您好,你已经有了上级代理,不能添加其他代理了!");
                }
            }else if(type.equals("1")){
                System.out.println("服务站代理");
                //服务站代理
                ProxyStationService proxyUserService = ((ProxyStationService) SpringUtil.getBean("ProxyStationService"));
                YmProxyStation ymProxyStation=new YmProxyStation();
                ymProxyStation.setUserId(userId);
                ymProxyStation.setStationId(Long.parseLong(pm1));
                Integer check = proxyUserService.selectCheckProxyStation(ymProxyStation);
                if(check==0){
                    Integer result = proxyUserService.insertProxyStation(ymProxyStation);
                    if(result>0){
                        YmVStation ymVStation=new YmVStation();
                        ymVStation.setStationId(Long.parseLong(pm1));
                        List<YmVStation> list = ((VaccineStationService) SpringUtil.getBean("VaccineStationService")).queryVaccineStationDetailSer(ymVStation);
                        tm.setContent("你的代理服务站为:"+list.get(0).getStationName());
                        System.out.println("新增代理服务站成功");
                    }else{
                        System.out.println("新增代理服务站失败");
                    }
                }else{
                    System.out.println("亲爱的用户您好,你已经有了代理服务站,不能添加其他代理了!");
                   tm.setContent("亲爱的用户您好,你已经有了代理服务站,不能添加其他代理了!");
                }
            }else{
                System.out.println("错误的参数");
                throw new RuntimeException("错误的参数");
            }

        }
        //tm.setContent(se.getEventKey() + se.getTicket());
        return tm;
    }

    @Override
    public void eLocation(LocationEvent le) {
        System.out.println("地理事件事件");
    }

    @Override
    public BasicMsg eScanCodePush(ScanCodeEvent sce) {
        System.out.println(" 处理二维码扫描事件消息");
        TextMsg tm = new TextMsg(sce);
        tm.setContent(Strings.join("\n", sce.getEventKey(), sce.getScanType(), sce.getScanResult()));
        return tm;
    }

    @Override
    public BasicMsg eScanCodeWait(ScanCodeEvent sce) {
        System.out.println("扫码推事件且弹出“消息接收中”提示框");
        return this.eScanCodePush(sce);
    }

    @Override
    public BasicMsg ePicSysPhoto(SendPhotosEvent spe) {
        System.out.println(" 处理弹出系统拍照发图的事件推送");
        TextMsg tm = new TextMsg(spe);
        tm.setContent(Strings.join("\n",
                                   spe.getEventKey(),
                                   String.valueOf(spe.getSendPicsInfo().getCount()),
                                   String.valueOf(spe.getSendPicsInfo().getPicList()),
                                   String.valueOf(spe.getSendPicsInfo()
                                                     .getPicList()
                                                     .get(0)
                                                     .getPicMd5Sum())));
        return tm;
    }

    @Override
    public BasicMsg ePicPhotoOrAlbum(SendPhotosEvent spe) {
        System.out.println("处理弹出拍照或者相册发图的事件推送");

        return this.ePicSysPhoto(spe);
    }

    @Override
    public BasicMsg ePicWeixin(SendPhotosEvent spe) {
        System.out.println("处理弹出微信相册发图器的事件推送");
        return this.ePicSysPhoto(spe);
    }

    @Override
    public BasicMsg eLocationSelect(SendLocationInfoEvent slie) {
        System.out.println("处理弹出地理位置选择器的事件推送消息");
        TextMsg tm = new TextMsg(slie);
        tm.setContent(Strings.join("\n",
                                   slie.getLocationX(),
                                   slie.getLocationY(),
                                   slie.getLabel(),
                                   String.valueOf(slie.getScale()),
                                   slie.getPoiname()));
        return tm;
    }

    @Override
    public void eSentTmplJobFinish(SentTmlJobEvent stje) {
        System.out.println("处理模板发送事件消息");

    }

    @Override
    public void eSentAllJobFinish(SentAllJobEvent saje) {
        System.out.println("处理群发消息事件消息");
    }


}
